package com.mpdbailey.cleverdicandroid;

import java.util.List;

import android.os.AsyncTask;

import com.pigdogbay.androidutils.utils.WordList;
import com.pigdogbay.androidutils.utils.WordListCallback;
import com.pigdogbay.androidutils.utils.WordSearch;
import com.pigdogbay.androidutils.utils.WordSearch.SearchType;

public class AnagramPresenter
{
	IAnagramView _View;
	WordList _WordList;
	WordSearch _WordSearch;
	boolean _DictionaryLoaded = false, _Searching = false, _IgnoreThreadUpdates=false;
	
	public void SetFindSubAngrams(boolean value)
	{
		_WordSearch.setFindSubAnagrams(value);
	}
	public void SetResultLimit(int limit)
	{
		_WordList.SetResultLimit(limit);
	}
	public void SetDictionary(List<String> wordList)
	{
		_WordList.SetWordList(wordList);
		_DictionaryLoaded = wordList!=null;
	}

	public AnagramPresenter(IAnagramView view)
	{
		_View = view;
		_WordList = new WordList();
		_WordSearch = new WordSearch(_WordList);
	}

	public void Clear()
	{
		stopSearch();
		_IgnoreThreadUpdates=true;
		_View.clearMatches();
		_View.setStatus("",false);
		_View.setQuery("");
		_View.setError(null);
	}
	public void stopSearch(){
		if (_WordList!=null){
			_WordList.stop();
		}
	}

	private boolean IsQueryOK(String query)
	{
		if (isNullOrBlank(query))
		{
			_View.setError(_View.getStringResource(R.string.EntryErrorMessage));
			return false;
		}
		if (!_DictionaryLoaded)
		{
			_View.setError(_View.getStringResource(R.string.DictionaryNotLoaded));
			return false;
		}
		_View.setError(null);
		return true;
	}

	public void Search()
	{
		if (_Searching)
		{
			return;
		}
		String query = _View.getQuery();
		if (!IsQueryOK(query))
		{
			return;
		}
		_IgnoreThreadUpdates=false;
		_View.clearMatches();
		_Searching = true;
		_View.setStatus(_View.getStringResource(R.string.Searching),true);
		this.new BackgroundWorker().execute(query);
	}

	private static boolean isNullOrBlank(String param)
	{
		return param == null || param.trim().length() == 0;
	}
	/*
	 * Removes formatting such as missing letters
	 * eg 'be (e)' becomes 'be'
	 */
	public static String RemoveFormatting(String result)
	{
		int index = result.indexOf(" (");
		return index==-1 ? result : result.substring(0,index);
	}
	

	private class BackgroundWorker extends AsyncTask<String, String, Void> implements WordListCallback
	{
		int numOfMatches = 0;
		SearchType _SearchType;
		
		@Override
		protected Void doInBackground(String... params)
		{
			try
			{
				numOfMatches = 0;
				String query = params[0];
				//tidy up, convert numbers into dots
				query = _WordSearch.preProcessQuery(query);
				_SearchType = _WordSearch.getQueryType(query);
				//remove illegal characters
				query = _WordSearch.postProcessQuery(query, _SearchType);
				_WordSearch.runQuery(query, _SearchType, BackgroundWorker.this);
				
			} catch (Exception e)
			{
			}
			return null;
		}
		@Override
		protected void onProgressUpdate(String... values)
		{
			if (!_IgnoreThreadUpdates)
			{
				_View.addMatch(values[0]);
			}
		}

		@Override
		protected void onPostExecute(Void result)
		{
			if (!_IgnoreThreadUpdates){
			_View.setStatus(_View.getStringResource(R.string.MatchesFound)+Integer.valueOf(numOfMatches).toString(),false);
			}
			_Searching = false;
			_View.trackQuery(WordSearch.toString(_SearchType));
		}
		@Override
		public void Update(String result)
		{
			if (!_IgnoreThreadUpdates)
			{
				numOfMatches++;
				publishProgress(result);
			}
			
		}
	}
}
